<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入班型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班型级别" prop="modelType">
        <el-select v-model="queryParams.modelType" placeholder="请选择班型级别" clearable size="small">
          <el-option
            v-for="dict in modelTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--
      <el-form-item label="最大选班轮数" prop="maxSelectTimes">
        <el-input
          v-model="queryParams.maxSelectTimes"
          placeholder="请输入最大选班轮数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="换发新教材是否免费" prop="freeBookFlag">
        <el-select v-model="form.freeBookFlag" placeholder="请选择换发新教材是否免费" clearable size="small">
            <el-option
            v-for="dict in freeBookFlagOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
          </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      -->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:classModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:classModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:classModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:classModel:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="班型ID" align="center" prop="modelId" />-->
      <el-table-column label="班型名称" align="center" prop="modelName" />
      <el-table-column label="班型级别" :formatter="modelTypeFormat" align="center" prop="modelType" />
      <el-table-column label="班型价格" align="center" prop="price" />
      <el-table-column label="最大选班轮数" align="center" prop="maxSelectTimes" />
      <el-table-column label="换发新教材免费" :formatter="freeBookFlagFormat" align="center" prop="freeBookFlag" />
      <el-table-column label="ICON" align="center" prop="url">
        <template slot-scope="scope">
          <img :src=" baseApi + scope.row.url" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:classModel:edit']"
          >修改</el-button>
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleQryModelAttr(scope.row)"
            v-hasPermi="['edu:classModel:edit']"
          >属性</el-button>
          -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:classModel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班型信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!--
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane label="基本信息" name="first">
            -->
            <el-form-item label="班型名称" prop="modelName">
              <el-input v-model="form.modelName" placeholder="请输入班型名称" />
            </el-form-item>
            <el-form-item label="班型级别" prop="modelType">
              <el-select v-model="form.modelType" placeholder="请选择班型级别">
                <el-option
                  v-for="dict in modelTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="最大选班轮数" prop="maxSelectTimes">
              <el-input v-model="form.maxSelectTimes" placeholder="请输入最大选班轮数" />
            </el-form-item>
            <el-form-item label="班型价格" prop="price">
              <el-input v-model="form.price" 
                @keyup.native="proving($event)" 
                @input="editInput($event,'plan')" placeholder="请输入班型价格" />
            </el-form-item>
            <el-form-item label="换发新教材免费" prop="freeBookFlag">
              <el-select v-model="form.freeBookFlag" placeholder="请选择换发新教材是否免费">
                <el-option
                  v-for="dict in freeBookFlagOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="附件名称" prop="attachName">
              <el-input disabled v-model="form.attachName" placeholder="请输入附件名称" />
            </el-form-item>
            <el-form-item label="附件路径" prop="url">
              <el-upload
                ref="upload"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                :file-list="fileList"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
              </el-upload>
              <el-form-item>
                <el-button type="primary" @click="submitFileForm">上 传</el-button>
              </el-form-item>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                    >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
            </el-form-item>
            <!--
          </el-tab-pane>
          <el-tab-pane label="班型属性" name="second" style="height:500px">
            <el-button size="mini" type="primary"
              icon="el-icon-plus" @click="addModelAttr()">新增属性</el-button>
            <div style="margin: 15px 0;"></div>
            <el-row  style="margin-left: -115px;" v-for="(item,index) in modelAttrList" :key="index">
                 <el-col :span="6">
                   <el-form-item label="">
                      <treeselect style="width:200px" v-model="item.campusId" :options="campusOptions" 
                            :multiple="false" :disableBranchNodes="true"
                            :show-count="true" placeholder="请选择归属校区" />
                    </el-form-item>
                 </el-col>
                 <el-col :span="5">
                   <el-form-item label="">
                    <el-input v-model="item.price" style="width:150px" placeholder="请输入班型价格" />
                  </el-form-item>
                 </el-col>
                 <el-col :span="5">
                   <el-form-item label="">
                      <el-select v-model="item.status" style="width:150px" placeholder="请选择状态" clearable size="small">
                        <el-option
                              v-for="dict in statusOptions"
                              :key="dict.dictValue"
                              :label="dict.dictLabel"
                              :value="dict.dictValue"
                            />
                      </el-select>
                    </el-form-item>
                 </el-col>
                 <el-col :span="8">
                   <div style="text-align:center;">
                    <el-button size="mini" type="danger"
                      icon="el-icon-delete" v-if="modelAttrList.length > 1" 
                      @click="delModelAttr(index)">删除</el-button>
                   </div>
                 </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClassModel, getClassModel, delClassModel, addClassModel, updateClassModel, exportClassModel } from "@/api/edu/classModel";
import { treeselectByType } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import { matchFileType } from "@/utils/base";

export default {
  name: "ClassModel",
  components: { Treeselect },
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班型信息表格数据
      classModelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      statusOptions: [],
      campusOptions: [],
      modelTypeOptions: [],
      freeBookFlagOptions: [],
      activeName: "first",
      modelAttrList: [{
        campusId: null,
        price: null,
        status: null
      }],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        modelType: null,
        maxSelectTimes: null,
        freeBookFlag: null,
        status: null,
      },
      // 表单参数
      form: {},
      fileList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 表单校验
      rules: {
        modelType: [
          { required: true, message: "班型级别不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "班型价格不能为空", trigger: "change" }
        ],
        maxSelectTimes: [
          { required: true, message: "最大选班轮数不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.queryCampus();
    this.getDicts("edu_model_type").then(response => {
      this.modelTypeOptions = response.data;
    });
    this.getDicts("exam_free_book_flag").then(response => {
      this.freeBookFlagOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });

    this.getList();
  },
  methods: {
    queryCampus() {
      // 查询校区（deptType = 1）
      treeselectByType("1").then(response => {
        this.campusOptions = response.data;
      })
    },
    // 任务组名字典翻译
    modelTypeFormat(row, column) {
      return this.selectDictLabel(this.modelTypeOptions, row.modelType);
    },
    // 
    freeBookFlagFormat(row, column) {
      return this.selectDictLabel(this.freeBookFlagOptions, row.freeBookFlag);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 查询班型信息列表 */
    getList() {
      this.loading = true;
      listClassModel(this.queryParams).then(response => {
        this.classModelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.modelAttrList = [{
        campusId: null,
        price: null,
        status: null,
        attachId: null,
        attachName: null,
        url: null,
      }]

      this.form = {
        modelId: null,
        modelName: null,
        modelType: null,
        price: null,
        maxSelectTimes: null,
        freeBookFlag: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        eduModelAttrList: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班型信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getClassModel(modelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班型信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let flag = true
          if(matchFileType(this.form.attachName).toString() !== 'image') {
            this.msgError("附件不是图片");
            flag = false
          }

          this.form.eduModelAttrList = []
          this.modelAttrList.forEach(model =>{
            this.form.eduModelAttrList.push({
              campusId: model.campusId,
              price: model.price,
              status: model.status
            })
          })
          if(flag) {
            if (this.form.modelId != null) {
              updateClassModel(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addClassModel(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$confirm('是否确认删除班型信息编号为"' + modelIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delClassModel(modelIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有班型信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportClassModel(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleTabChange() {
      if("second" === this.activeName) {
        //console.log(JSON.stringify(this.form.eduModelAttrList))
        if(this.form.eduModelAttrList.length > 0) {
          this.modelAttrList = [] //.splice(0,1) // 删除原来的空行
          this.form.eduModelAttrList.forEach(model => {
            this.modelAttrList.push({
              campusId: model.campusId,
              price: model.price,
              status: model.status
            })
          })
        }
      } else {
        if(this.modelAttrList.length > 0) {
          // 其它情况需要临时保存已编辑为保存的属性
          this.form.eduModelAttrList = []
          this.modelAttrList.forEach(model =>{
            this.form.eduModelAttrList.push({
              campusId: model.campusId,
              price: model.price,
              status: model.status
            })
          })
        }
        
      }
    },
    addModelAttr() {
      //console.log(this.classSubjects.length)
      this.modelAttrList.push({
        campusId: null,
        price: null,
        status: null,
        })
    },
    delModelAttr(index) {
      if(this.modelAttrList.length > 1) {
        this.modelAttrList.splice(index,1)
      } else {
        this.msgError("至少有一个属性");
      }
    },
    handleQryModelAttr(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getClassModel(modelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班型信息";
        this.activeName = "second"
        this.handleTabChange()
      });
      
    },
    proving(e){
      var val=e.target.value;
      //限制只能输入一个小数点
      if (val.indexOf(".") != -1) {
        var str = val.substr(val.indexOf(".") + 1);
        if (str.indexOf(".") != -1) {
          val = val.substr(0, val.indexOf(".") + str.indexOf(".") + 1);
        }
      }
      e.target.value = val.replace(/[^\d^\.]+/g,'');

    },
    editInput(value, name) {
      this.form[name] = ("" + value) // 第一步：转成字符串
                      .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
                      .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
                      .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
                      .match(/^\d*(\.?\d{0,1})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },
    //******** */ upload start
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.form.url = response.url
      this.form.attachName = file.name
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleRemove(file, fileList) {
      //console.log(file, fileList);
      this.form.url = null
    },
    //******** */ upload end
  }
};
</script>
<style lang="scss" scoped>
.user-avatar {
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 10px;
          }
</style>
